package com.sion.servicekeep;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ServiceInfo;
import android.os.Build;
import android.os.IBinder;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.core.app.NotificationCompat;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ForegroundService extends Service {
    private static final String TAG = "ForegroundService";
    private static final String CHANNEL_ID = "ServiceKeepChannel";
    private static final int NOTIFICATION_ID = 1001;
    private static final String PREF_NAME = "AppSettings";
    private static final String KEY_DAEMON_START = "daemon_start_enabled";

    private Handler timeUpdateHandler;
    private Runnable timeUpdateRunnable;
    private NotificationManager notificationManager;
    private SimpleDateFormat timeFormat;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "ForegroundService created");
        // 初始化通知管理器（提前获取，避免空指针）
        notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (notificationManager == null) {
            Log.e(TAG, "NotificationManager is null, service may not work");
        }
        createNotificationChannel();

        // 初始化时间格式化器
        timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());

        // 初始化时间更新处理器（主线程Handler）
        timeUpdateHandler = new Handler(Looper.getMainLooper());
        timeUpdateRunnable = new Runnable() {
            @Override
            public void run() {
                updateNotification();
                timeUpdateHandler.postDelayed(this, 1000); // 每秒更新
            }
        };
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null; // 非绑定服务
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String startedBy = intent != null ? intent.getStringExtra("startedBy") : "Unknown";
        Log.d(TAG, "ForegroundService started by: " + startedBy);

        // 检查守护启动开关状态
        SharedPreferences sharedPreferences = getSharedPreferences(PREF_NAME, MODE_PRIVATE);
        boolean isDaemonStartEnabled = sharedPreferences.getBoolean(KEY_DAEMON_START, false);

        if (isDaemonStartEnabled) {
            try {
                // 1. 创建最小化通知（仅保留必要字段）
                Notification notification = createBasicNotification();
                if (notification == null) {
                    Log.e(TAG, "Failed to create notification, aborting");
                    stopSelf();
                    return START_NOT_STICKY;
                }

                // 2. 启动前台服务（适配高版本系统类型要求）
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
                    int serviceType = getValidForegroundServiceType();
                    startForeground(NOTIFICATION_ID, notification, serviceType);
                    Log.d(TAG, "Started foreground service with type: " + serviceType);
                } else {
                    startForeground(NOTIFICATION_ID, notification);
                    Log.d(TAG, "Started foreground service (legacy)");
                }

                // 3. 启动时间更新
                startTimeUpdates();
                Log.d(TAG, "Foreground service started successfully");

            } catch (Exception e) {
                Log.e(TAG, "Critical error in onStartCommand: " + e.getMessage(), e);
                stopSelf();
                return START_NOT_STICKY;
            }
        }

        return START_STICKY; // 服务被杀死后尝试重启
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "ForegroundService destroyed");
        stopTimeUpdates(); // 停止时间更新
    }

    /**
     * 获取适配当前系统的前台服务类型（避免类型不匹配导致崩溃）
     */
    private int getValidForegroundServiceType() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
            // Android 12+：使用通用的数据同步类型（需在Manifest声明权限）
            return ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC;
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            // Android 10-11：使用特殊用途类型
            return ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE;
        } else {
            return 0;
        }
    }

    /**
     * 创建最小化通知（仅包含系统强制要求的字段）
     */
    private Notification createBasicNotification() {
        try {
            // 点击通知打开主页面
            Intent notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
            notificationIntent.putExtra("startedBy", "ForegroundService");

            // 创建PendingIntent（使用IMMUTABLE确保兼容性）
            PendingIntent pendingIntent = PendingIntent.getActivity(
                    this,
                    0,
                    notificationIntent,
                    PendingIntent.FLAG_IMMUTABLE | PendingIntent.FLAG_UPDATE_CURRENT
            );

            // 构建通知（仅保留必要字段）
            return new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("保活服务运行中") // 强制要求
                    .setContentText("点击返回应用") // 强制要求
                    .setSmallIcon(android.R.drawable.ic_dialog_info) // 强制要求（系统内置图标，避免资源问题）
                    .setContentIntent(pendingIntent)
                    .setOngoing(true) // 禁止滑动删除
                    .setPriority(NotificationCompat.PRIORITY_LOW)
                    .setChannelId(CHANNEL_ID)
                    .build();

        } catch (Exception e) {
            Log.e(TAG, "Failed to create basic notification: " + e.getMessage(), e);
            return null;
        }
    }

    /**
     * 创建通知渠道（Android 8.0+必需）
     */
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && notificationManager != null) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "保活服务通知", // 渠道名称
                    NotificationManager.IMPORTANCE_LOW // 低重要性，避免打扰用户
            );
            channel.setDescription("用于维持应用保活服务的运行");
            channel.setSound(null, null); // 关闭声音
            channel.enableVibration(false); // 关闭震动
            notificationManager.createNotificationChannel(channel);
            Log.d(TAG, "Notification channel created: " + CHANNEL_ID);
        }
    }

    /**
     * 启动时间更新
     */
    private void startTimeUpdates() {
        if (timeUpdateHandler != null && timeUpdateRunnable != null) {
            timeUpdateHandler.removeCallbacks(timeUpdateRunnable); // 先移除旧任务
            timeUpdateHandler.post(timeUpdateRunnable);
            Log.d(TAG, "Time update started");
        }
    }

    /**
     * 停止时间更新
     */
    private void stopTimeUpdates() {
        if (timeUpdateHandler != null && timeUpdateRunnable != null) {
            timeUpdateHandler.removeCallbacks(timeUpdateRunnable);
            Log.d(TAG, "Time update stopped");
        }
    }

    /**
     * 更新通知内容（显示当前时间）
     */
    private void updateNotification() {
        if (notificationManager == null) return;

        try {
            Notification updatedNotification = new NotificationCompat.Builder(this, CHANNEL_ID)
                    .setContentTitle("保活服务运行中")
                    .setContentText("当前时间: " + timeFormat.format(new Date()))
                    .setSmallIcon(android.R.drawable.ic_dialog_info)
                    .setContentIntent(PendingIntent.getActivity(
                            this,
                            0,
                            new Intent(this, MainActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
                            PendingIntent.FLAG_IMMUTABLE
                    ))
                    .setOngoing(true)
                    .setPriority(NotificationCompat.PRIORITY_LOW)
                    .setChannelId(CHANNEL_ID)
                    .build();

            notificationManager.notify(NOTIFICATION_ID, updatedNotification);
        } catch (Exception e) {
            Log.e(TAG, "Failed to update notification: " + e.getMessage(), e);
        }
    }
}